package sn.ugb.cours.jee.zd.hibernate.sessions;

import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 943529636178791686L;

	private String _configFilePath = "/hibernate.cfg.xml";

	public static final String SESSION_FACTORY_KEY = SessionFactory.class
			.getName();

	private SessionFactory sessionFactory = null;

	public SessionFactory getHibernateSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void destroy() {
		try {
			sessionFactory.close();
		} catch (HibernateException e) {
			System.out.println("Unable to close Hibernate Session Factory: "
					+ e.getMessage());
		}

	}

	public void initHibernateSessionFactoryForMe() throws ServletException {
		System.out.println("*************************************");
		System.out
				.println("**** Initilizing Hibernate session Factory **********");
		Configuration configuration = null;

		URL configFileURL = null;

		try {
			configFileURL = HibernateServlet.class.getResource(_configFilePath);
			configuration = (new Configuration()).configure(configFileURL);
			sessionFactory = configuration.buildSessionFactory();
		} catch (HibernateException e) {
			System.out.println("Initializing hibernate error: "
					+ e.getMessage());
		}
		System.out.println("*************************************");

	}

	public void setConfigFilePath(String configFilePath) {
		if ((configFilePath == null) || (configFilePath.trim().length() == 0)) {
			throw new IllegalArgumentException(
					"configFilePath cannot be empty or null.");
		}

		System.out.println("Setting 'configFilePath' to '" + configFilePath
				+ "'...");
		_configFilePath = configFilePath;
	}

}